﻿namespace ConsoleApp;

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class HeartbeatClient
{
    private const int HeartbeatInterval = 5000; // 5 seconds
    private const string ServerAddress = "yourserveraddress.com"; // Replace with your server address
    private const int ServerPort = 12345; // Replace with your server port
    private TcpClient client;
    private NetworkStream stream;

    public HeartbeatClient()
    {
        // Set up the timer to send heartbeats
        var heartbeatCallback = new TimerCallback(SendHeartbeat);
        var heartbeatTimer = new Timer(heartbeatCallback, null, HeartbeatInterval, HeartbeatInterval);
    }

    private void ConnectToServer()
    {
        client = new TcpClient(ServerAddress, ServerPort);
        stream = client.GetStream();
    }

    private void SendHeartbeat(object state)
    {
        if (stream != null && stream.CanWrite)
        {
            try
            {
                // Prepare the heartbeat message (e.g., a simple string)
                var heartbeatMessage = "Heartbeat";
                var messageBytes = Encoding.ASCII.GetBytes(heartbeatMessage);

                // Send the heartbeat to the server
                stream.Write(messageBytes, 0, messageBytes.Length);
                Console.WriteLine("Heartbeat sent to server.");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error sending heartbeat: " + ex.Message);
                // Handle the exception, e.g., reconnect or notify the user
            }
        }
        else
        {
            Console.WriteLine("Not connected to the server. Attempting to connect...");
            ConnectToServer();
        }
    }

    // Ensure to disconnect and dispose resources when the client is closing
    public void DisconnectFromServer()
    {
        if (stream != null)
        {
            stream.Close();
            stream = null;
        }

        if (client != null)
        {
            client.Close();
            client = null;
        }
    }
}